<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:numb:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:numb:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:numb:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:numb:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="dialogVisible = true">修改题目名称</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="numbList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column v-for="(item, index) in titleList" :label="item.name + '数量'" align="center"
        :prop="item.id + 'examNum'" />

      <el-table-column v-for="(item, index) in titleList" :label="item.name + '分数'" align="center"
        :prop="item.id + 'examScore'" />
      <el-table-column align="center" :label="'考试时间'" :prop="'examinationTime'" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:numb:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:numb:remove']">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 题目重命名 -->
    <el-dialog title="修改题目类型信息" :visible.sync="dialogVisible" width="30%">

      <el-dialog width="30%" title="请输入新增题目类型名称" :visible.sync="innerVisible" append-to-body>
        <el-form style="width: 80%;">
          <el-form-item label="新题目类型名称">
            <div class="titleItem">
              <el-input v-model="newTitle.name" placeholder="请输入自定义名称" style="margin: 0px 20px;"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="新题目类型名称">
            <div class="titleItem">
              <el-radio-group v-model="newTitle.type">
                <el-radio label="单选"></el-radio>
                <el-radio label="多选"></el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addOneTitle">确 定</el-button>
          <el-button @click="innerVisible = false">取 消</el-button>
        </span>
      </el-dialog>

      <el-form style="width: 80%;">
        <el-form-item v-for="(item, index) in this.titleList" :key="item.id" :label="item.name + '名称'">
          <div class="titleItem">
            <div style="width: 40px;margin-left: 10px; font-size: small; color: rgb(24,144,255);">
              <span v-if="item.type == 1">单选</span>
              <span v-else-if="item.type == 2">多选</span>
              <span v-else>暂无类型</span>
            </div>
            <el-input v-model="titleList[index].name" placeholder="请输入自定义名称" style="margin: 0px 20px;"></el-input>
            <el-button type="danger" icon="el-icon-delete" @click="delOneTitle(item.id)" size="mini"></el-button>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="innerVisible = true">添加题目类型</el-button>
        <el-button type="primary" @click="tabled">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 添加或修改默认考试数量对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" style="display: flex;">
        <div class="example_box">
          <el-form-item v-for="(item, index) in titleList" :key="item.id" :prop="item.id + 'QuestionNumb'">
            <div style="display: flex; align-items: center;">
              <p class="text">{{ item.name }}</p>
              <p class="text">数量</p>
            </div>
            <el-input v-model="form[item.id + 'QuestionNumb']" placeholder="请输入题目数量" />
          </el-form-item>
          <!-- 输入考试时间 -->
          <el-form-item>
            <div style="display: flex; align-items: center;">
              <p class="text">考试时间</p>
            </div>
            <el-input v-model="form['examinationTime']" placeholder="请输入考试时间" />
          </el-form-item>
        </div>

        <div class="example_box">
          <el-form-item v-for="(item, index) in titleList" :key="item.id" :prop="item.id + 'QuestionScore'">
            <div style="display: flex; align-items: center;">
              <p class="text">{{ item.name }}</p>
              <p class="text">分数</p>
            </div>
            <el-input v-model="form[item.id + 'QuestionScore']" placeholder="请输入题目分数" />
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNumb, getNumb, delNumb, addNumb, updateNumb, updateTitleNames, addTitleClass, delTitleClass } from "@/api/exam/numb";

export default {
  name: "Numb",
  data() {
    return {
      dialogVisible: false,
      innerVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 默认考试数量表格数据
      numbList: [],
      idList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        a1QuestionNumb: null,
        a2QuestionNumb: null,
        a34QuestionNumb: null,
        bQuestionNumb: null,
        xQuestionNumb: null,
        a1QuestionScore: null,
        a2QuestionScore: null,
        a34QuestionScore: null,
        bQuestionScore: null,
        xQuestionScore: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //
      nameLists: [],
      newTitle: {
        name: '',
        type: ''
      }
    };
  },
  created() {
    this.$store.dispatch('titleName/INIT_NAME').then(() => {
      this.getList();
    });
  },
  methods: {
    /* 提交考试名称*/
    tabled() {
      updateTitleNames(this.titleList).then(response => {
        this.dialogVisible = false;
        window.location.reload();
      })
    },
    addOneTitle() {
      console.log(this.newTitle);
      let type = ''
      if (this.newTitle.type == "单选") {
        type = '1'
      } else if (this.newTitle.type == "多选") {
        type = '2'
      }

      addTitleClass(this.newTitle.name, type).then(() => {
        console.log(this.newTitle.name);
        console.log(type);
        this.$store.dispatch('titleName/INIT_NAME');
      })
      this.innerVisible = false;
      window.location.reload();
    },
    delOneTitle(id) {
      delTitleClass(id).then(() => {
        this.dialogVisible = false;
        window.location.reload();
      })
    },

    /** 查询默认考试数量列表 */
    getList() {
      this.loading = true;
      for (let i of this.titleList) {
        this.$set(this.form, i.id + "QuestionNumb", "")
        this.$set(this.form, i.id + "QuestionScore", "")
      }
      this.$set(this.form, "examinationTime", "")


      listNumb().then((response) => {
        console.log("____row____");
        this.numbList = []
        for (let i = 0; i < response.rows.length; i++) {
          let row_info = response.rows
          let date_obj = {
            examinationTime: row_info[i].examinationTime
          }

          for (let j of row_info[i].examNum.split(';')) {
            let titleId = j.split('@')[0];
            let examNum = j.split('@')[1];

            date_obj['id'] = row_info[i].id
            date_obj[titleId + 'examNum'] = examNum
          }

          for (let j of row_info[i].examScore.split(';')) {
            let titleId = j.split('@')[0];
            let examScore = j.split('@')[1];

            date_obj[titleId + 'examScore'] = examScore
          }

          this.numbList.push(date_obj);
        }

        let flag = 0
        for (let i = 0; i < this.titleList.length; i++) {
          let j = response.rows[0].examNum.split(';')[i]
          let titleId = j.split('@')[0];
          let titleName = this.titleList[i]['name'] || ""
          let data = {
            titleId,
            titleName
          }
          this.idList.push(data)
          flag += 1
        }

        console.log('this.numbList:');
        console.log(this.numbList);

        console.log('this.idList:');
        console.log(this.idList);

        this.total = response.total;
        this.loading = false;
        console.log("____row____");

      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      for (let i of this.titleList) {
        this.$set(this.form, i.id + "QuestionNumb", "")
        this.$set(this.form, i.id + "QuestionScore", "")
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加默认考试数量";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log("row = ");
      console.log(row);
      const id = row.id || this.ids
      console.log("发送id为" + id);
      console.log("调用getNumb ing");
      getNumb(id).then(response => {
        this.reset()
        // console.log(response);
        this.$set(this.form, "id", id[0])
        this.open = true;
        this.title = "修改默认考试数量";
        console.log("调用getNumb end");
      });


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log("form = ");
          console.log(this.form);
          if (this.form.id != null) {
            // console.log("form = ");
            // console.log(this.form);
            console.log("进入修改");
            let examNum = ""
            let examScore = ""
            for (let i = 0; i < this.titleList.length; i++) {
              examNum += this.titleList[i].id + '@' + (this.form[this.titleList[i].id + 'QuestionNumb'] || "0") + ';'
              examScore += this.titleList[i].id + '@' + (this.form[this.titleList[i].id + 'QuestionScore'] || "0") + ';'
            }
            let data = {
              id: this.form.id,
              examNum,
              examScore,
              examinationTime: this.form.examinationTime || "0"
            }
            console.log("data:");
            console.log(data);
            updateNumb(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              console.log("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log('_____add______');
            console.log(this.form);
            // console.log(this.titleList());
            let examNum = ""
            let examScore = ""
            for (let i = 0; i < this.titleList.length; i++) {
              examNum += this.titleList[i].id + '@' + (this.form[this.titleList[i].id + 'QuestionNumb'] || "0") + ';'
              examScore += this.titleList[i].id + '@' + (this.form[this.titleList[i].id + 'QuestionScore'] || "0") + ';'
            }
            let data = {
              examNum,
              examScore,
              examinationTime: this.form.examinationTime || "0"
            }
            console.log("data:");
            console.log(data);
            addNumb(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除默认考试数量编号为"' + ids + '"的数据项？').then(function () {
        return delNumb(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/numb/export', {
        ...this.queryParams
      }, `numb_${new Date().getTime()}.xlsx`)
    },
  },
  computed: {
    titleList() {
      return this.$store.state.titleName.questionType
    }
  }
};
</script>

<style>
.example_box {
  width: 50%;
  padding: 0px 10px;
  margin: 0px 10px 300px;
  /* background-color: aqua; */
}

.text {
  line-height: 0px;
  font-size: 24px;
  font-weight: bold;
}

.titleItem {
  display: flex;
  flex-wrap: nowrap;
}
</style>
